import { Repository, UpdateResult } from "typeorm";
import { DaoBase } from "../../src/engine/dao/DaoBase";
import { MysqlClient } from "../../src/engine/utils/MySqlClient";
import { MysqlManager } from "../../src/engine/utils/MysqlManager";
import { UserRoomEntity } from "../entity/UserRoomEntity";

export class UserRoomDao extends DaoBase {

    public static Tb_Name: string = "t_user_room";

    public static async getRepository() {
        let repository: Repository<UserRoomEntity> = await this.getRepositoryBase(UserRoomEntity, this.getGameDbName())
        return repository;
    }

    public static async update_user(userid: number, room_id: number) {
        let entity: UserRoomEntity = new UserRoomEntity()
        entity.userid = userid
        entity.room_id = room_id
        let repository: Repository<UserRoomEntity> = await this.getRepository()
        let result: UserRoomEntity
        if (!repository.hasId(entity)) {
            result = await repository.save(entity)
        } else {
            let updateResult: UpdateResult = await repository.update({ userid: entity.userid }, entity)
            // { generatedMaps: [], raw: [], affected: 1 }
            if (updateResult && updateResult.affected > 0) {
                result = entity
            }
        }
        return result
    }


    public static async getUser(userid: number) {
        let repository: Repository<UserRoomEntity> = await this.getRepository()
        let entity: UserRoomEntity = await repository.findOneBy({
            userid: userid
        })
        if (!entity) {
            entity = new UserRoomEntity()
            entity.userid = userid
            entity.room_id = 0
        }
        return entity
    }



}